package main

import (
	"time"
	"github.com/xfio/internal/db"
)

// getAllWorkers 在控制器内部获取所有Worker数据
func getAllWorkers(database *db.DB) ([]interface{}, error) {
	// 从数据库获取workers
	workers, err := database.GetWorkers()
	if err != nil {
		return []interface{}{}, err
	}

	// 将Worker结构体转换为interface{}数组
	var result []interface{}
	for _, worker := range workers {
		workerMap := map[string]interface{}{
			"id":                           worker.ID,
			"name":                         worker.Name,
			"ip_address":                   worker.IPAddress,
			"status":                       worker.Status,
			"heartbeat_status":             worker.HeartbeatStatus,
			"last_heartbeat":               worker.LastHeartbeat.Format(time.RFC3339),
			"created_at":                   worker.CreatedAt.Format(time.RFC3339),
			"consecutive_heartbeat_failures": worker.ConsecutiveHeartbeatFailures,
			"consecutive_heartbeat_success":  worker.ConsecutiveHeartbeatSuccess,
			"fio_version":                  worker.FIOVersion,
			"fio_status":                   worker.FIOStatus,
		}

		// 添加系统信息（如果存在）
		if worker.SystemInfo != nil {
			// 将SystemInfo转换为interface{}
			sysInfoMap := map[string]interface{}{
				"cpu_info":       worker.SystemInfo.CPUInfo,
				"cpu_cores":      worker.SystemInfo.CPUCores,
				"memory_total":   worker.SystemInfo.MemoryTotal,
				"memory_used":    worker.SystemInfo.MemoryUsed,
				"memory_free":    worker.SystemInfo.MemoryFree,
				"memory_percent": worker.SystemInfo.MemoryPercent,
				"os":             worker.SystemInfo.OS,
				"kernel":         worker.SystemInfo.Kernel,
				"arch":           worker.SystemInfo.Arch,
				"uptime":         worker.SystemInfo.Uptime,
			}
			workerMap["system_info"] = sysInfoMap
		}

		// 添加磁盘信息（如果存在）
		if worker.DiskInfo != nil {
			var diskInfoInterfaces []interface{}
			for _, disk := range worker.DiskInfo {
				diskInfoMap := map[string]interface{}{
					"name":         disk.Name,
					"mount_point":  disk.MountPoint,
					"total_space":  disk.TotalSpace,
					"used_space":   disk.UsedSpace,
					"free_space":   disk.FreeSpace,
					"used_percent": disk.UsedPercent,
					"file_system":  disk.FileSystem,
				}
				diskInfoInterfaces = append(diskInfoInterfaces, diskInfoMap)
			}
			workerMap["disk_info"] = diskInfoInterfaces
		}

		result = append(result, workerMap)
	}

	return result, nil
}

// getWorkerByID 在控制器内部获取指定ID的Worker数据
func getWorkerByID(database *db.DB, workerID string) (map[string]interface{}, error) {
	worker, err := database.GetWorker(workerID)
	if err != nil {
		return map[string]interface{}{}, err
	}

	// 将Worker转换为interface{}
	workerMap := map[string]interface{}{
		"id":                           worker.ID,
		"name":                         worker.Name,
		"ip_address":                   worker.IPAddress,
		"status":                       worker.Status,
		"heartbeat_status":             worker.HeartbeatStatus,
		"last_heartbeat":               worker.LastHeartbeat.Format(time.RFC3339),
		"created_at":                   worker.CreatedAt.Format(time.RFC3339),
		"consecutive_heartbeat_failures": worker.ConsecutiveHeartbeatFailures,
		"consecutive_heartbeat_success":  worker.ConsecutiveHeartbeatSuccess,
		"fio_version":                  worker.FIOVersion,
		"fio_status":                   worker.FIOStatus,
	}

	// 添加系统信息（如果存在）
	if worker.SystemInfo != nil {
		sysInfoMap := map[string]interface{}{
			"cpu_info":       worker.SystemInfo.CPUInfo,
			"cpu_cores":      worker.SystemInfo.CPUCores,
			"memory_total":   worker.SystemInfo.MemoryTotal,
			"memory_used":    worker.SystemInfo.MemoryUsed,
			"memory_free":    worker.SystemInfo.MemoryFree,
			"memory_percent": worker.SystemInfo.MemoryPercent,
			"os":             worker.SystemInfo.OS,
			"kernel":         worker.SystemInfo.Kernel,
			"arch":           worker.SystemInfo.Arch,
			"uptime":         worker.SystemInfo.Uptime,
		}
		workerMap["system_info"] = sysInfoMap
	}

	// 添加磁盘信息（如果存在）
	if worker.DiskInfo != nil {
		var diskInfoInterfaces []interface{}
		for _, disk := range worker.DiskInfo {
			diskInfoMap := map[string]interface{}{
				"name":         disk.Name,
				"mount_point":  disk.MountPoint,
				"total_space":  disk.TotalSpace,
				"used_space":   disk.UsedSpace,
				"free_space":   disk.FreeSpace,
				"used_percent": disk.UsedPercent,
				"file_system":  disk.FileSystem,
			}
			diskInfoInterfaces = append(diskInfoInterfaces, diskInfoMap)
		}
		workerMap["disk_info"] = diskInfoInterfaces
	}

	return workerMap, nil
}

// getPendingTasksForWorker 获取Worker的待处理任务
func getPendingTasksForWorker(database *db.DB, workerID string) ([]interface{}, error) {
	// 直接使用数据库查询获取待处理任务
	tasks, err := database.GetPendingTasksForWorker(workerID)
	if err != nil {
		return []interface{}{}, err
	}

	// 将Task结构体转换为interface{}数组
	var result []interface{}
	for _, task := range tasks {
		taskMap := map[string]interface{}{
			"id":          task.ID,
			"test_case_id": task.TestCaseID,
			"worker_id":   task.WorkerID,
			"status":      task.Status,
			"created_at":  task.CreatedAt.Format(time.RFC3339),
		}
		// 如果有开始时间和结束时间，也添加它们
		if task.StartTime != nil {
			taskMap["start_time"] = task.StartTime.Format(time.RFC3339)
		}
		if task.EndTime != nil {
			taskMap["end_time"] = task.EndTime.Format(time.RFC3339)
		}
		result = append(result, taskMap)
	}

	return result, nil
}